const Koa = require('koa')
const app = new Koa()


// 视图引擎
const views = require('koa-views')

// JSON解析
const json = require('koa-json')

// 错误捕获
const onerror = require('koa-onerror')

// 数据解析
const bodyparser = require('koa-bodyparser')

// 日志
const logger = require('koa-logger')

// token
const { bindToken, tokenErr } = require('./util/token') 

// error handler
onerror(app)

app.use(tokenErr)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

// token
bindToken(app)

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
require('./routes/index')(app)

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
